package com.sx.core.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.security.NoSuchAlgorithmException;

public class ThreeDESUtils {
    static SecretKeyFactory keyFactory = null;
    static {
        try {
            keyFactory = SecretKeyFactory.getInstance("DESede");
        } catch (NoSuchAlgorithmException e) {
        }
    }
    public static String encrypt(String key,String src)
    {
        try{
            DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("UTF-8"));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
            SecretKey securekey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, securekey);
            byte[] b=cipher.doFinal(src.getBytes("UTF-8"));
            return Hex.encodeHexString(b).toUpperCase();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    public static String decrypt(String key,String src) {
        try{
//            byte[] bytesrc = Hex.decodeHex(src.toCharArray());
            byte[] bytesrc = Base64.decodeBase64(src.getBytes());
            DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("UTF-8"));
            SecretKey securekey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, securekey);
            byte[] retByte = cipher.doFinal(bytesrc);
            return new String(retByte);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;

    }
    public static void main(String[] args) throws Exception{
        String password = "deviceId=a3574189164082483cb6b76a3b16&username=15982146822";//密码
//        System.out.println("加密前的字符串:" + "qqqqqq的");
//        String encoded = encrypt("1858391058118583910581ab","qqqqqq的");
//        System.out.println("加密key:" + "1858391058118583910581ab");
//        System.out.println("加密后的字符串:" + encoded);
//        String srcBytes = decrypt("1858391058118583910581ab",encoded);
//        System.out.println("解密后的字符串:" + (srcBytes));
//
        String de="E593A6E696B9E6B395";

        System.out.println(decrypt("55qE",de));
        System.out.println(Hex.encodeHexString("kdk快快快快快".getBytes()));
        System.out.println(Hex.encodeHexString("kdk快快快快快".getBytes()).toUpperCase());



    }

}